<?php
/**
 * Created by PhpStorm.
 * User: DD
 * Date: 2016/6/13
 * Time: 23:17
 */

namespace app\common\util\weixin;


use app\common\util\CUrl;
use think\Config;
use think\Exception;

class AccessToken
{
    private static $appId;
    private static $secretId;

    public static function config($appId, $secretId)
    {
        if (empty($appId) || empty($secretId)) {
            throw new Exception('appid and secret can not be empty');
        }
        self::$secretId = $secretId;
        self::$appId = $appId;
    }

    public static function getAppId()
    {
        return self::$appId;
    }

    public static function getSecretId()
    {
        return self::$secretId;
    }

    /**
     * 获取微信Access_Token
     */
    public static function getAccessToken()
    {
        $token = self::_getAccessToken();
        if (!$token) {
            $token = self::_fetchAccessToken();
        }
        return $token;
    }

    private static function _getAccessToken()
    {
        $token = S('access_token');
        if ($token) {
            return $token;
        }
        return false;
    }

    private static function _fetchAccessToken()
    {
        if (empty(self::$appId)) {
            trace('appid is none');
            throw new Exception('appid and secret can not be empty');
        }
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . self::$appId . '&secret=' . self::$secretId;
        $accessToken = json_decode(CUrl::httpGet($url), true);
        if (!isset($accessToken['access_token'])) {
            trace('获取ACCESS_TOKEN失败', 'error');
            return false;
        }
        S('access_token', $accessToken['access_token'], 7000);
        return $accessToken['access_token'];
    }


}

AccessToken::config(Config::get('weixin.ccnn_appid'), Config::get('weixin.ccnn_appsecret'));